<?php
require_once(SITE_ROOT . 'config/constants.conf.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBTraining.class.php');
require_once(SITE_ROOT . 'class/db/DBTrainingType.class.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Training.class.php');
require_once(SITE_ROOT . 'class/bean/TrainingType.class.php');
require_once(SITE_ROOT . 'class/logic/TrainingTableRow.class.php');
require_once(SITE_ROOT . 'class/Exceptions.class.php');
require_once(SITE_ROOT . 'lib/PHT.php');

class LogicTraining {

	private $countries;
	private $trainingtypes;

	private static $instance;

	private function __construct() {
		$dbcountry = new DBCountry();
		$this->countries = $dbcountry->getCountries();
		$dbtrainingtype = new DBTrainingType();
		$this->trainingtypes = $dbtrainingtype->getTrainingTypes();
	}

	public static function getInstance() {
		if(!isset(self::$instance)) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function getTrainingTypes() {
		return $this->trainingtypes;
	}
	
	public function createTrainingTable() {
		$table = array();
		
		$dbtraining = new DBTraining();
		$date = $dbtraining->getLatestDate();
		
		if (count($this->countries) > 0) {
			foreach ($this->countries as $index => &$country) {
				$trainings_db = $dbtraining->getTraining(null, $country, $date);
				$trainings = new ArrayObject();
				
				$iteratorTT = $this->getTrainingTypes()->getIterator();
				$iteratorT = $trainings_db->getIterator();					
				foreach ($iteratorTT as $i => $trainingtype) {
					$training = $iteratorT->current();
					if (isset($training) && $trainingtype->getTrainingTypeID() == $training->getTrainingType()->getTrainingTypeID()) {
						$trainings->append($training);
						$training = $iteratorT->next();
					}
					else {
						$trainings->append(new Training($trainingtype, $country, $date, 0, 0));
					}
				}
				
				$row = new TrainingTableRow($index+1, $country, $trainings, $this->trainingtypes);
				$table[$country->getCountryID()] = $row;
			}
		}
		return $table;
	}
	
}

?>